﻿using System;
using System.Windows.Forms;
using Alerter.DataSet;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;

namespace Alerter.Controls
{
    public partial class MessageListUserControl : UserControl, IList, IGridView
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.MessageSaved += delegate { SetGridDataSource(); };
                SetGridDataSource();
            }
        }

        #endregion

        public MessageListUserControl()
        {
            InitializeComponent();
            ApplyStateStyle();
            gridView.DoubleClick += GridViewDoubleClick;
            gridView.CustomUnboundColumnData += GridViewCustomUnboundColumnData;
        }

        #region Private Methods

        private void ApplyStateStyle()
        {
            var sentStyleFormatCondition = new StyleFormatCondition();
            sentStyleFormatCondition.Appearance.ForeColor = System.Drawing.Color.Green;
            sentStyleFormatCondition.Appearance.Options.UseForeColor = true;
            sentStyleFormatCondition.ApplyToRow = true;
            sentStyleFormatCondition.Column = colEstado;
            sentStyleFormatCondition.Condition = FormatConditionEnum.Equal;
            sentStyleFormatCondition.Value1 = MessageState.Enviada.ToString();

            var notSentStyleFormatCondition = new StyleFormatCondition();
            notSentStyleFormatCondition.Appearance.ForeColor = System.Drawing.Color.Red;
            notSentStyleFormatCondition.Appearance.Options.UseForeColor = true;
            notSentStyleFormatCondition.ApplyToRow = true;
            notSentStyleFormatCondition.Column = colEstado;
            notSentStyleFormatCondition.Condition = FormatConditionEnum.Equal;
            notSentStyleFormatCondition.Value1 = MessageState.NaoEnviada.ToString();

            var partiallySentStyleFormatCondition = new StyleFormatCondition();
            partiallySentStyleFormatCondition.Appearance.ForeColor = System.Drawing.Color.Orange;
            partiallySentStyleFormatCondition.Appearance.Options.UseForeColor = true;
            partiallySentStyleFormatCondition.ApplyToRow = true;
            partiallySentStyleFormatCondition.Column = colEstado;
            partiallySentStyleFormatCondition.Condition = FormatConditionEnum.Equal;
            partiallySentStyleFormatCondition.Value1 = MessageState.ParcialmenteEnviada.ToString();

            var toSendStyleFormatCondition = new StyleFormatCondition();
            toSendStyleFormatCondition.Appearance.ForeColor = System.Drawing.Color.Blue;
            toSendStyleFormatCondition.Appearance.Options.UseForeColor = true;
            toSendStyleFormatCondition.ApplyToRow = true;
            toSendStyleFormatCondition.Column = colEstado;
            toSendStyleFormatCondition.Condition = FormatConditionEnum.Equal;
            toSendStyleFormatCondition.Value1 = MessageState.AEnviar.ToString();

            gridView.FormatConditions.AddRange(new[] { sentStyleFormatCondition, notSentStyleFormatCondition, partiallySentStyleFormatCondition, toSendStyleFormatCondition });
        }

        //private void SetupContactLookupData()
        //{
        //    contactoDataSet = _controller.GetContacts();
        //    contactRepositoryItemLookUpEdit.Columns.Clear();
        //    contactRepositoryItemLookUpEdit.Columns.AddRange(new[] {
        //        new LookUpColumnInfo("Id", "Id", 81, FormatType.None, "", false, HorzAlignment.Near),
        //        new LookUpColumnInfo("Nome", "Nome", 85, FormatType.None, "", true, HorzAlignment.Near)});
        //    contactRepositoryItemLookUpEdit.DisplayMember = contactoDataSet.Contacto.NomeColumn.ColumnName;
        //    contactRepositoryItemLookUpEdit.ValueMember = contactoDataSet.Contacto.IdColumn.ColumnName;
        //    contactRepositoryItemLookUpEdit.DataSource = contactoDataSet.Contacto;
        //}

        private void SetupMessageTypeLookupData()
        {
            tipoMensagemDataSet = _controller.GetMessageTypes();
            messageTypeRepositoryItemLookUpEdit.Columns.Clear();
            messageTypeRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Id", "Id", 81, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Nome", "Nome", 85, FormatType.None, "", true, HorzAlignment.Near)});
            messageTypeRepositoryItemLookUpEdit.DisplayMember = tipoMensagemDataSet.TipoMensagem.NomeColumn.ColumnName;
            messageTypeRepositoryItemLookUpEdit.ValueMember = tipoMensagemDataSet.TipoMensagem.IdColumn.ColumnName;
            messageTypeRepositoryItemLookUpEdit.DataSource = tipoMensagemDataSet.TipoMensagem;
        }

        private void SetGridDataSource()
        {
            MensagemDataSet dataSet = _controller.GetMessages();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.Mensagem.TableName;
            SetupMessageTypeLookupData();
        }

        private void ShowMessage(long documentId)
        {
            var window = new MessageXtraForm { DocumentId = documentId, Controller = _controller };
            window.ShowDialog();
        }

        #endregion

        public void AddDocument()
        {
            ShowMessage(-1);
        }

        public void DeleteDocument()
        {
            var document = (MensagemDataSet.MensagemRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (document == null)
                return;
            var result = MessageBox.Show(_controller.OwnerWindow, string.Format("'{0}' será eliminada definitivamente.", document.Descricao),
                 "Mensagem", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            if (result != DialogResult.OK)
                return;
            _controller.DeleteMessage(document.Id);
        }
        
        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "Message"; }
        }

        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var message = (MensagemDataSet.MensagemRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (message == null)
                return;
            ShowMessage(message.Id);
        }

        void GridViewCustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            var message = (MensagemDataSet.MensagemRow)gridView.GetDataRow(e.RowHandle);
            if (message == null || e.Column != colContactos)
                return;
            e.Value = message.GetContactoRows().Length;
        }
    }
}
